package com.example.lots_of_demo.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.lots_of_demo.security.SecurityUser;
import com.example.lots_of_demo.utils.DateUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author : LZJ
 * @description : MYBATIS-PLUS 自动填充拦截器
 * @date : 2021/2/21
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增时填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 先判断是否存在 创建时间 字段
        boolean createDateTime = metaObject.hasSetter("createDateTime");
        // 先判断是否存在 创建者ID 字段
        boolean createId = metaObject.hasSetter("createId");
        // 先判断是否存在 创建者 字段
        boolean creator = metaObject.hasSetter("creator");
        if (createDateTime) {
            strictInsertFill(metaObject, "createDateTime", String.class, DateUtils.getCurrentDateTime());
        }
        if (createId) {
            strictInsertFill(metaObject, "createId", Long.class, user.getUserId());
        }
        if (creator) {
            strictInsertFill(metaObject, "creator", String.class, user.getUsername());
        }
    }

    /**
     * 修改时填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
    }
}
